﻿using AutoMapper;
using MediatR;
using SU.Center.Domain.RBAC;
using SU.Center.Infa;
using System.Security.Claims;

namespace SU.Center.Api.Handler.RBAC
{
    /// <summary>
    /// 获取权限树
    /// </summary>
    public class GetTreePermissionListHandler : IRequestHandler<GetTreePermissionListRepsultDto, ApiResult>
    {
        private readonly IBaseReposiotry<Permissions> _permissionRepository;
        private readonly IBaseReposiotry<UserRoles> _userRolesRepository;
        private readonly IBaseReposiotry<RolePermissions> _rolesRepository;
        private readonly ILogger<GetTreePermissionListHandler> _logger;
        private readonly IMapper mapper;
        private readonly IHttpContextAccessor _contextAccessor;

        public GetTreePermissionListHandler(IBaseReposiotry<Permissions> permissionRepository, IBaseReposiotry<UserRoles> userRolesRepository, IBaseReposiotry<RolePermissions> rolesRepository, ILogger<GetTreePermissionListHandler> logger, IMapper mapper, IHttpContextAccessor contextAccessor)
        {
            _permissionRepository = permissionRepository;
            _userRolesRepository = userRolesRepository;
            _rolesRepository = rolesRepository;
            _logger = logger;
            this.mapper = mapper;
            _contextAccessor = contextAccessor;
        }

        public async Task<ApiResult> Handle(GetTreePermissionListRepsultDto request, CancellationToken cancellationToken)
        {
            var list = await GetTree(0);
            var user = _contextAccessor.HttpContext.User;
            var UserId = user.FindFirst("userId")?.Value;
            //当前用户对应的权限ID

            var userRoles = await _userRolesRepository.GetsAll(x => x.UserRolesId == int.Parse(UserId)&& x.IsDeleted == false);

           var roleIds = userRoles.Select(x => x.RolesId).ToArray();

            var userPermissions = await _rolesRepository.GetsAll(x => roleIds.Contains(x.RoleId) && x.IsDeleted == false);
            var PermissionIds = userPermissions.Select(x => x.PermissionId).ToArray();
            list = list.Where(x => PermissionIds.Contains(x.PermissionsId)).ToList();
            return ApiResult.Ok(list);
        }

        public async Task<List<GetTreePermissionListResponseDto>> GetTree(int parentId = 0)
        {
            var Tree = await _permissionRepository.GetsAll(x => x.ParentId == parentId);
            var result = mapper.Map<List<GetTreePermissionListResponseDto>>(Tree);
            foreach (var item in result)
            {
                item.children = await GetTree(item.PermissionsId);
            }
            return result;
        }


    }
}
public class GetTreePermissionListRepsultDto : IRequest<ApiResult>
{

}

public class GetTreePermissionListResponseDto
{
    public int PermissionsId { get; set; }

    public string PermissionsName { get; set; }
    public string? path { get; set; }

    public string? name { get; set; }

    public string? component { get; set; }

    public IList<GetTreePermissionListResponseDto> children { get; set; }
}